package hu.bme.aut.consulttime.client.components;

import hu.bme.aut.consulttime.client.StudentService;
import hu.bme.aut.consulttime.client.StudentServiceAsync;
import hu.bme.aut.consulttime.entitydtos.UserDTO;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ModifyStudentPassword extends DialogBox {
	// Proxy to studentService
	private StudentServiceAsync studentService = GWT
			.create(StudentService.class);
	
	private Label lblUname;
	private TextBox textBoxPass;
	
	public ModifyStudentPassword(final long id, final String userName) {
		super(true);
		
		FormPanel formPanel = new FormPanel();
		formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
		setWidget(formPanel);
		formPanel.setSize("100%", "100%");
		
		VerticalPanel verticalPanel = new VerticalPanel();
		formPanel.setWidget(verticalPanel);
		verticalPanel.setSize("100%", "100%");
		
		lblUname = new Label("Modify '"+userName+"' user:");
		verticalPanel.add(lblUname);
		
		textBoxPass = new TextBox();
		textBoxPass.setText("<Enter New Password>");
		verticalPanel.add(textBoxPass);
		
		Button btnNewButton = new Button("Save");
		btnNewButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				UserDTO userDTO = new UserDTO();
				userDTO.setUserId(id);
				userDTO.setPassword(textBoxPass.getText());
				
		        studentService.updateStudentPassword(userDTO, new AsyncCallback<Boolean>() {
					
					@Override
					public void onSuccess(Boolean result) {
						if(result == true){
							Window.confirm("'"+ userName + "' user's password modified!");
//					        //Refresh the table
//					        StudentPage.loadStudents();
						}else{
							Window.alert("Password modification failed!");
						}
					}
					
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Remote Procedure Call - Failure");
					}
				});
			}
		});
		verticalPanel.add(btnNewButton);
		verticalPanel.setCellHorizontalAlignment(btnNewButton, HasHorizontalAlignment.ALIGN_CENTER);
	}

}
